use std::collections::VecDeque;
use std::sync::Arc;
use tokio::sync::{Mutex, mpsc};

// 导入数据定义
use super::data::*;

/// 数据处理器
pub struct DataProcessor {
    config: DataProcessorConfig,
    parse_state: ParseState,
    current_frame: Option<DataFrame>,
    // 接收缓冲区
    buffer: Vec<u8>,
    // 已解析的帧队列
    frame_queue: Arc<Mutex<VecDeque<DataFrame>>>,
    // 处理结果发送通道
    result_sender: mpsc::Sender<ProcessResult>,
}

impl DataProcessor {
    /// 创建新的数据处理器
    pub fn new(config: DataProcessorConfig, result_sender: mpsc::Sender<ProcessResult>) -> Self {
        DataProcessor {
            config,
            parse_state: ParseState::WaitingForHeader,
            current_frame: None,
            buffer: Vec::new(),
            frame_queue: Arc::new(Mutex::new(VecDeque::new())),
            result_sender,
        }
    }

    /// 获取帧队列的引用
    pub fn frame_queue(&self) -> Arc<Mutex<VecDeque<DataFrame>>> {
        self.frame_queue.clone()
    }

    /// 处理原始字节数据
    pub async fn process_raw_data(&mut self, data: &[u8]) {
        println!("收到原始数据: {:X?}", data);
        // 将新数据添加到缓冲区
        self.buffer.extend_from_slice(data);
        
        // 解析缓冲区中的数据
        self.parse_buffer().await;
    }

    /// 解析缓冲区中的数据
    async fn parse_buffer(&mut self) {
        while !self.buffer.is_empty() {
            match self.parse_state {
                ParseState::WaitingForHeader => {
                    // 查找帧头
                    if let Some(pos) = self.buffer.iter().position(|&b| b == self.config.frame_header) {
                        // 移除帧头前的所有数据
                        self.buffer.drain(0..pos);
                        // 移除帧头本身
                        self.buffer.remove(0);
                        
                        // 初始化新帧
                        self.current_frame = Some(DataFrame {
                            header: self.config.frame_header,
                            device_addr: 0,
                            cmd: 0,
                            data_len: 0,
                            data: Vec::new(),
                            checksum: 0,
                            footer: 0,
                            timestamp: DataFrame::get_timestamp_ms(),
                        });
                        
                        // 进入下一状态
                        self.parse_state = ParseState::ReadingDeviceAddr;
                    } else {
                        // 未找到帧头，清空缓冲区
                        self.buffer.clear();
                        break;
                    }
                }
                
                ParseState::ReadingDeviceAddr => {
                    if self.buffer.is_empty() {
                        break;
                    }
                    
                    if let Some(frame) = &mut self.current_frame {
                        frame.device_addr = self.buffer.remove(0);
                        self.parse_state = ParseState::ReadingCmd;
                    }
                }
                
                ParseState::ReadingCmd => {
                    if self.buffer.is_empty() {
                        break;
                    }
                    
                    if let Some(frame) = &mut self.current_frame {
                        frame.cmd = self.buffer.remove(0);
                        self.parse_state = ParseState::ReadingDataLen;
                    }
                }
                
                ParseState::ReadingDataLen => {
                    if self.buffer.is_empty() {
                        break;
                    }
                    
                    if let Some(frame) = &mut self.current_frame {
                        frame.data_len = self.buffer.remove(0) as usize;
                        
                        // 检查数据长度是否合法
                        if frame.data_len > self.config.max_data_length {
                            let err_msg = format!("数据长度超出最大值: {} > {}", 
                                               frame.data_len, self.config.max_data_length);
                            let _ = self.result_sender.send(ProcessResult::ParseError(err_msg)).await;
                            
                            // 重置解析状态
                            self.reset_parser();
                            continue;
                        }
                        
                        if frame.data_len == 0 {
                            self.parse_state = ParseState::ReadingChecksum;
                        } else {
                            self.parse_state = ParseState::ReadingData(0);
                        }
                    }
                }
                
                ParseState::ReadingData(progress) => {
                    let remaining = if let Some(frame) = &self.current_frame {
                        frame.data_len - progress
                    } else {
                        self.reset_parser();
                        continue;
                    };
                    
                    let take = std::cmp::min(remaining, self.buffer.len());
                    
                    if let Some(frame) = &mut self.current_frame {
                        frame.data.extend_from_slice(&self.buffer[0..take]);
                        self.buffer.drain(0..take);
                        
                        let new_progress = progress + take;
                        if new_progress >= frame.data_len {
                            self.parse_state = ParseState::ReadingChecksum;
                        } else {
                            self.parse_state = ParseState::ReadingData(new_progress);
                        }
                    }
                }
                
                ParseState::ReadingChecksum => {
                    if self.buffer.is_empty() {
                        break;
                    }
                    
                    if let Some(frame) = &mut self.current_frame {
                        frame.checksum = self.buffer.remove(0);
                        self.parse_state = ParseState::ReadingFooter;
                    }
                }
                
                ParseState::ReadingFooter => {
                    if self.buffer.is_empty() {
                        break;
                    }
                    
                    let footer = self.buffer.remove(0);
                    
                    if let Some(mut frame) = self.current_frame.take() {
                        frame.footer = footer;
                        
                        // 检查帧尾是否正确
                        if footer != self.config.frame_footer {
                            let err_msg = format!("帧尾错误: 收到0x{:X}, 预期0x{:X}", 
                                               footer, self.config.frame_footer);
                            let _ = self.result_sender.send(ProcessResult::ParseError(err_msg)).await;
                            self.reset_parser();
                            continue;
                        }
                        
                        // 校验和检查
                        if self.config.enable_checksum {
                            let calculated = self.calculate_checksum(&frame);
                            if calculated != frame.checksum {
                                let _ = self.result_sender.send(ProcessResult::ChecksumError {
                                    calculated,
                                    received: frame.checksum
                                }).await;
                                self.reset_parser();
                                continue;
                            }
                        }
                        
                        // 处理帧数据
                        self.process_frame(frame).await;
                    }
                    
                    // 解析完成，重置状态准备下一帧
                    self.reset_parser();
                }
            }
        }
    }

    /// 处理完整的数据帧
    async fn process_frame(&mut self, frame: DataFrame) {
        // 检查命令是否支持
        if !self.is_command_supported(frame.cmd) {
            let _ = self.result_sender.send(ProcessResult::UnsupportedCommand(frame.cmd)).await;
            return;
        }
        
        // 根据命令类型进行不同处理
        match frame.cmd {
            0x01 => self.process_measurement_data(&frame).await,
            0x02 => self.process_status_data(&frame).await,
            0x03 => self.process_config_data(&frame).await,
            0x04 => self.process_error_data(&frame).await,
            _ => {} // 已在is_command_supported中检查
        }
        
        // 将处理后的帧加入队列
        let mut queue = self.frame_queue.lock().await;
        queue.push_back(frame.clone());
        
        // 发送成功结果
        let _ = self.result_sender.send(ProcessResult::Success(frame)).await;
    }

    /// 处理测量数据(示例)
    async fn process_measurement_data(&self, frame: &DataFrame) {
        println!("处理测量数据 - 设备: 0x{:X}, 数据长度: {}", frame.device_addr, frame.data_len);
    }

    /// 处理状态数据(示例)
    async fn process_status_data(&self, frame: &DataFrame) {
        println!("处理状态数据 - 设备: 0x{:X}, 数据长度: {}", frame.device_addr, frame.data_len);
    }

    /// 处理配置数据(示例)
    async fn process_config_data(&self, frame: &DataFrame) {
        println!("处理配置数据 - 设备: 0x{:X}, 数据长度: {}", frame.device_addr, frame.data_len);
    }

    /// 处理错误数据(示例)
    async fn process_error_data(&self, frame: &DataFrame) {
        println!("处理错误数据 - 设备: 0x{:X}, 数据长度: {}", frame.device_addr, frame.data_len);
    }

    /// 计算校验和
    fn calculate_checksum(&self, frame: &DataFrame) -> u8 {
        let mut checksum = frame.device_addr;
        checksum = checksum.wrapping_add(frame.cmd);
        checksum = checksum.wrapping_add((frame.data_len / 2) as u8);  // 数据长度/2
        for &byte in &frame.data {
            checksum = checksum.wrapping_add(byte);
        }
        checksum
    }

    /// 检查命令是否支持
    fn is_command_supported(&self, cmd: u8) -> bool {
        matches!(cmd, 0x01 | 0x02 | 0x03 | 0x04)
    }

    /// 重置解析器状态
    fn reset_parser(&mut self) {
        self.parse_state = ParseState::WaitingForHeader;
        self.current_frame.take();
    }

    /// 构建响应帧
    pub fn build_response_frame(&self, device_addr: u8, cmd: u8, data: &[u8]) -> DataFrame {
        let data_len = data.len();
        
        let mut frame = DataFrame {
            header: self.config.frame_header,
            device_addr,
            cmd,
            data_len,
            data: data.to_vec(),
            checksum: 0,
            footer: self.config.frame_footer,
            timestamp: DataFrame::get_timestamp_ms(),
        };
        
        if self.config.enable_checksum {
            frame.checksum = self.calculate_checksum(&frame);
        }
        
        frame
    }

    /// 将数据帧转换为发送用的字节流
    pub fn frame_to_bytes(frame: &DataFrame) -> Vec<u8> {
        let mut bytes = Vec::new();
        
        bytes.push(frame.header);
        bytes.push(frame.device_addr);
        bytes.push(frame.cmd);
        bytes.push(frame.data_len as u8);
        bytes.extend_from_slice(&frame.data);
        bytes.push(frame.checksum);
        bytes.push(frame.footer);
        
        bytes
    }
}

// 示例测试
#[cfg(test)]
mod tests {
    use super::*;
    use tokio::sync::mpsc;

    #[tokio::test]
    async fn test_data_processing() {
        let (sender, mut receiver) = mpsc::channel(100);
        let config = DataProcessorConfig::default();
        let mut processor = DataProcessor::new(config, sender);
        
        // 测试帧数据
        let test_frame = [
            0xAA, 0x01, 0x01, 0x04, 0x00, 0x01, 0x02, 0x03, 0x0A, 0x55
        ];
        
        processor.process_raw_data(&test_frame).await;
        
        if let Some(result) = receiver.recv().await {
            match result {
                ProcessResult::Success(frame) => {
                    assert_eq!(frame.device_addr, 0x01);
                    assert_eq!(frame.cmd, 0x01);
                }
                _ => panic!("处理结果不符合预期"),
            }
        }
    }
}
